#include "KMPString.h"

KMPString::KMPString()
{
	mSource = "";
	mTarget = "";
	pos = 0;
}
KMPString::KMPString(std::string& src, std::string& tar, int& pos)
{
	mSource = src;
	mTarget = tar;
	pos = 0;
	getNext();
	pos = getPos();
}

void KMPString::setSource(std::string& src)
{
	this->mSource = src;
	return;
}
void KMPString::setTarget(std::string& tar)
{
	this->mTarget = tar;
	return;
}
int KMPString::getPos()
{
	int i = 0;
	int j = 0;
	while (i < mSource.size())
	{
		if (mSource[i] == mTarget[j])
		{
			if (j == mTarget.size() - 1)
			{
				pos = i - j;
				return pos;
			}
			i++;
			j++;
		}
		else
		{
			j = mNext[j];
			if (j == -1)
			{
				i++;
				j++;
			}
		}
	}
	return -1;
}
int KMPString::getPos(std::string& tar)
{
	if (mSource.size() == 0)
		return -1;
	mTarget = tar;
	return getPos();
}
void KMPString::getNext()
{
	int i = 0;
	int j = -1;
	this->mNext.push_back(-1);
	while (i < mTarget.size())
	{
		if (-1 == j || mTarget[i] == mTarget[j])
		{
			i++;
			j++;
			mNext.push_back(j);
		}
		else
		{
			j = mNext[j];
		}
	}
}